﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Signage01.dao
{
    class ScreenTemplateLastIndexDAO
    {
        string serializationFile = "resources/screen/screentemplateLastIndex.bin";
        //private List<Timeline> listTimeline;
        static ScreenTemplateLastIndexDAO screenTemplateLastIndexDAO = null;

        private ScreenTemplateLastIndexDAO()
        {

        }

        public static ScreenTemplateLastIndexDAO getSingleTon()
        {
            if (screenTemplateLastIndexDAO == null)
            {
                screenTemplateLastIndexDAO = new ScreenTemplateLastIndexDAO();
            }
            return screenTemplateLastIndexDAO;
        }

        public  List<int> getAll()
        {
            // retrieving the list from the file
            try
            {
                using (Stream stream = File.Open(serializationFile, FileMode.OpenOrCreate))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                    // if this line throws exception, the file is empty, so we have to create a new list in catch block
                    List<int> listTemp = (List<int>)bformatter.Deserialize(stream);
                    return listTemp;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("The file is empty");
                List<int> listTemp = new List<int>();
                return listTemp;
            }
        }

        public int saveListToFile(List<int> listTemp)
        {
            try
            {
                // saving the list to the file
                using (Stream stream = File.Open(serializationFile, FileMode.OpenOrCreate))
                {
                    var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bformatter.Serialize(stream, listTemp);
                    stream.Close();
                }
                return 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine("save excepiton is:" + ex.ToString());
                return 0;
            }
        }

    }
}
